<script lang="ts" setup>
import { ChatLineRound, Share, Star } from '@element-plus/icons-vue'
import {
  expertDataList,
  getExpertList,
  userFollowDoctor,
  userFollowDoctorSelect,
  userUnFollowDoctor,
} from '~/api/home'
import { decode, encode } from '~/utils/base/dataEncry'

const dayjs = useDayjs()
const router = useRouter()
const TJlist = ref<any[]>([])
const listAll = ref<any[]>([])
const fileData = ref()
const activeName = ref('全部')
const title = ref('专家库')
const routePath = [{ name: '首页', path: '/' }, { name: title, type: 'back' }, { name: '专家详情', path: '' }]
const route = useRoute()
const { isLogin } = storeToRefs(useUserStore())

fileData.value = ref<any>({})
if (route.query.data) {
  fileData.value = decode(route.query.data)
}
else if (route.query.id) {
  await getDetail()
}
async function getDetail() {
  const id = route.query.id || route.params.id
  const req = {
    condition: [{
      colName: 'id',
      ruleType: 'eq',
      value: id,
    }],
  }
  const res = await getExpertList(req)
  fileData.value = res.data[0]
  return fileData.value
}
const queryParams = computed(() => {
  return {
    page: {
      rownumber: 10,
      pageNo: 1,
    },
    condition: [
      {
        colName: 'publisher',
        ruleType: 'eq',
        value: fileData.value.name,
      },
    ],
  }
})
const queryParams1 = computed(() => {
  return {
    page: {
      rownumber: 10,
      pageNo: 1,
    },
    condition: [
      {
        colName: 'publisher',
        ruleType: 'eq',
        value: fileData.value.name,
      },
      {
        colName: 'publish_type',
        ruleType: 'eq',
        value: '文章',
      },
    ],
  }
})
const queryParams2 = computed(() => {
  return {
    page: {
      rownumber: 10,
      pageNo: 1,
    },
    condition: [
      {
        colName: 'publisher',
        ruleType: 'eq',
        value: fileData.value.name,
      },
      {
        colName: 'publish_type',
        ruleType: 'eq',
        value: '视频',
      },
    ],
  }
})
const queryParams3 = computed(() => {
  return {
    page: {
      rownumber: 10,
      pageNo: 1,
    },
    condition: [
      {
        colName: 'publisher',
        ruleType: 'eq',
        value: fileData.value.name,
      },
      {
        colName: 'publish_type',
        ruleType: 'eq',
        value: '音频',
      },
    ],
  }
})
const queryParams4 = computed(() => {
  return {
    page: {
      rownumber: 10,
      pageNo: 1,
    },
    condition: [
      {
        colName: 'publisher',
        ruleType: 'eq',
        value: fileData.value.name,
      },
      {
        colName: 'publish_type',
        ruleType: 'eq',
        value: '问答',
      },
    ],
  }
})
function getData() {
  getExpertList().then((res) => {
    TJlist.value = res.data.slice(0, 3)
  }).catch(() => {
  })
}
onMounted(() => {
  getData()
  getDataList(queryParams.value)
})
function clickItem(item: any) {
  getExpertList({
    condition: [{ colName: 'uid', ruleType: 'eq', value: item.uid }],
  }).then((res) => {
    fileData.value = res.data[0]
  })
}

function handleClick(tab) {
  console.log(tab.props.name)
  if (tab.props.name === '文章') {
    getDataList(queryParams1.value)
  }
  else if (tab.props.name === '视频') {
    getDataList(queryParams2.value)
  }
  else if (tab.props.name === '音频') {
    getDataList(queryParams3.value)
  }
  else if (tab.props.name === '问答') {
    getDataList(queryParams4.value)
  }
  else {
    getDataList(queryParams.value)
  }
}
function toConsult(item) {
  if (!isLogin.value) {
    // loginVisible.value = true
    // showLogin()
    return ElMessage.error('请先登录')
  }
  navigateTo({
    path: `/peopleHealth/consult`,
    query: {
      data: encode(item),
    },
  })
}
function clickDataItem(item) {
  console.log(item)
  // if (item.info === '文章') {
  const params = {
    ...queryParams.value,
  }
  params.condition.push({
    colName: 'uid',
    ruleType: 'eq',
    value: item.uid,
  })
  expertDataList(params).then((res) => {
    navigateTo({
      path: `/peopleHealth/popularizationDetail/${res.data[0].id}&专家作品`,
      query: {
        backText: '专家信息',
      },
    })
  })
}
function getDataList(queryParam: any) {
  listAll.value = []
  expertDataList(queryParam).then((res) => {
    res.data.forEach((item) => {
      listAll.value.push({
        title: item.title_name,
        blurd: extractTextFromPTags(item.contents),
        info: item.publish_type,
        time: dayjs(item.release_time).format('YYYY-MM-DD'),
        url: getImgUrl(item.cover_file_name, true),
        viewNum: item.page_view_num,
        uid: item.uid,
      })
    })
    collectSelect()
  })
}
function extractTextFromPTags(htmlString: string) {
  const parser = new DOMParser()
  const doc = parser.parseFromString(htmlString, 'text/html')
  const pTags = doc.getElementsByTagName('p')
  let text = ''
  for (let i = 0; i < pTags.length; i++) {
    text += pTags[i]?.textContent
  }
  return text
}

const followFlag = ref(1)
const tempId = ref()
// 修改用户关注
function changeArticleFollow(id) {
  if (!isLogin.value) {
    // loginVisible.value = true
    // showLogin()
    return ElMessage.error('请先登录')
  }
  if (followFlag.value === 2) {
    const params = [{
      serviceName: 'srvjk_follow_delete',
      data: [{
        id: tempId.value,
      }],
      condition: [{
        colName: 'id',
        value: tempId.value,
        ruleType: 'eq',
      }],
    }]
    userUnFollowDoctor(params).then((res) => {
      collectSelect()
    })
  }
  else if (followFlag.value === 1) {
    const params = [{
      serviceName: 'srvjk_follow_add',
      data: [{
        expert_id: fileData.value.uid,
      }],
      condition: [],
    }]
    userFollowDoctor(params).then((res) => {
      collectSelect()
    })
  }
}
// 获取用户收藏
function collectSelect() {
  if (!isLogin.value) {
    // 未登录 不查询用户关注列表
    return
  }
  const params = {
    page: {
      pageNo: 1,
      rownumber: 10,
    },
    condition: [{
      // colName: "target_id",
      colName: 'expert_id',
      ruleType: 'eq',
      value: fileData.value.uid,
    }],
  }
  userFollowDoctorSelect(params).then((res) => {
    if (res.data.length != 0) {
      tempId.value = res.data[0].id
      followFlag.value = 2
    }
    else {
      followFlag.value = 1
    }
  })
}
</script>

<template>
  <div class="py-100px">
    <ClientOnly>
      <div class="px-40">
        <div class="bg-#fff">
          <CommonPageContainer
            :title="title"
            :path="routePath"
          >
            <div class="mt-20px flex justify-between">
              <div class="w-full bg-#F7F9FD">
                <div class="w-40% flex items-center p-5 text-size-18px">
                  <div
                    class="ml-[-50px] h-40px w-40px flex cursor-pointer items-center justify-center rounded-md"
                    style="
                                background: linear-gradient(159.97deg, rgba(206,234,158,1) -140.78%,rgba(53,179,137,1) 89.45%);"
                    @click="router.back()"
                  >
                    <div class="h-18px w-18px flex items-center justify-center rounded-50% bg-#fff">
                      <span
                        class="flex items-center -ml-2px"
                        text="#0E9472"
                      >&lt;</span>
                    </div>
                  </div>
                  <div class="pl-5 text-#0E9472 font-700">
                    健康科普专家
                  </div>
                </div>
                <div class="m-5 flex bg-#FFF p-5">
                  <div class="min-w-200px w-15% flex items-center justify-center">
                    <img
                      class="h-200px w-200px rounded-50%"
                      :src="getImgUrl(fileData.personal_img)"
                      alt=""
                    >
                  </div>
                  <div class="w-85% p-5">
                    <div class="flex items-center">
                      <div
                        class="font-bold"
                        text="#28A182 20px"
                      >
                        {{ fileData.name }}
                      </div>
                      <el-divider direction="vertical" />
                      <div
                        class="font-bold"
                        text="#28A182 20px"
                      >
                        {{ fileData.position }}
                      </div>
                    </div>
                    <div class="py-2 text-18px font-semibold">
                      <!-- <span>所属医院：</span><span>{{ fileData.organ_name }}</span> -->
                      <span>所属医院：</span><span>{{ fileData.work_unit }}</span>
                    </div>
                    <div class="py-2 text-18px font-semibold">
                      <span>所在科室：</span><span>{{ fileData.work_dept }}</span>
                      <!-- <span>所在科室：</span><span>{{ fileData.department_name }}</span> -->
                    </div>
                    <div class="py-2 text-18px font-semibold">
                      <span>就诊时间：</span><span>{{ fileData.work_time }}</span>
                    </div>
                    <div class="w-20% flex justify-between py-2">
                      <el-button
                        color="#52B49A"
                        :icon="ChatLineRound"
                        style="color:#FFF"
                        @click="toConsult(fileData)"
                      >
                        咨询
                      </el-button>
                      <!-- <el-button color="#52B49A" :icon="Star" plain
                                                @click="changeArticleCollect(fileData.id)">{{ -->
                      <el-button
                        color="#52B49A"
                        :icon="Star"
                        plain
                        @click="changeArticleFollow(fileData.id)"
                      >
                        {{
                          followFlag === 1 ? '关注' : '已关注' }}
                      </el-button>
                      <el-button
                        color="#52B49A"
                        :icon="Share"
                        plain
                        @click="copyUrl"
                      >
                        分享
                      </el-button>
                    </div>
                  </div>
                </div>
                <div class="m-5 bg-#FFF p-5">
                  <div class="flex items-center">
                    <span class="ml-10px inline-block h-8px w-8px bg-#0E9472" />
                    <span
                      class="pl-4 font-extrabold"
                      text="#28A182 20px"
                    >简介</span>
                  </div>
                  <div class="py-5">
                    {{ fileData.brief_introduction }}
                  </div>
                  <div class="flex items-center">
                    <span class="ml-10px inline-block h-8px w-8px bg-#0E9472" />
                    <span
                      class="pl-4 font-extrabold"
                      text="#28A182 20px"
                    >擅长</span>
                  </div>
                  <div class="py-5">
                    {{ fileData.be_good_at }}
                  </div>
                </div>
                <div class="m-5 bg-#FFF p-5">
                  <div class="flex items-center">
                    <span class="ml-10px inline-block h-8px w-8px bg-#0E9472" />
                    <span
                      class="pl-4 font-extrabold"
                      text="#28A182 20px"
                    >专家作品</span>
                  </div>
                  <div class="p-5">
                    <el-tabs
                      v-model="activeName"
                      class="demo-tabs"
                      @tab-click="handleClick"
                    >
                      <el-tab-pane
                        label="全部"
                        name="全部"
                      >
                        <PublicExpertList
                          :list="listAll"
                          @click-item="clickDataItem"
                        />
                      </el-tab-pane>
                      <el-tab-pane
                        label="文章"
                        name="文章"
                      >
                        <PublicExpertList
                          :list="listAll"
                          @click-item="clickDataItem"
                        />
                      </el-tab-pane>
                      <el-tab-pane
                        label="视频"
                        name="视频"
                      >
                        <PublicExpertList
                          :list="listAll"
                          @click-item="clickDataItem"
                        />
                      </el-tab-pane>
                      <el-tab-pane
                        label="音频"
                        name="音频"
                      >
                        <PublicExpertList
                          :list="listAll"
                          @click-item="clickDataItem"
                        />
                      </el-tab-pane>
                      <el-tab-pane
                        label="问答"
                        name="问答"
                      >
                        <PublicExpertList
                          :list="listAll"
                          @click-item="clickDataItem"
                        />
                      </el-tab-pane>
                    </el-tabs>
                  </div>
                </div>
              </div>
              <!-- <div class="ml-20px w-160px">
                <div>
                  <div
                    class="h-40px flex items-center rounded-tl rounded-tr px-10px py-5px"
                    style="background: linear-gradient(159.97deg, rgba(206,234,158,1) -140.78%,rgba(53,179,137,1) 89.45%);"
                  >
                    <img src="/img/tj.png" alt="">
                    <div class="pl-15px" text="#fff 16px">
                      推荐
                    </div>
                  </div>
                  <div class="rounded-bl rounded-br px-10px py-5px" border="2px solid #50bc8d">
                    <div
                      v-for="item in TJlist" :key="item.id"
                      class="w-100% flex flex-col cursor-pointer justify-between p-2" @click="clickItem(item)"
                    >
                      <img class="inline-block" :src="getImgUrl(item.personal_img)" alt="">
                      <div class="">
                        <div class="mt-5px flex justify-between">
                          <div class="" text="12px" hover="text-#0E9472">
                            {{ item.name }}
                          </div>
                          <div
                            class="p-1px"
                            style="background: linear-gradient(159.97deg, rgba(206,234,158,1) -140.78%,rgba(53,179,137,1) 89.45%);border-radius: 3px;"
                            text="#fff 12px"
                          >
                            {{ item.position || '' }}
                          </div>
                        </div>
                        <div text="12px" class="py-5px">
                          {{ item.work_unit }}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div> -->
            </div>
          </CommonPageContainer>
        </div>
      </div>
    </ClientOnly>
  </div>
</template>

<style scoped>
:deep() .el-tabs__item.is-active {
  color: #28a182;
}

:deep() .el-tabs__item {
  font-size: 18px;
  font-weight: 600;
}

/* :deep() .el-tabs__nav-wrap::after{
        background-color: #28A182;
    } */
:deep() .el-tabs__item:hover {
  color: #28a182;
}

/* 下划线颜色 */
:deep() .el-tabs__active-bar {
  background-color: #28a182;
}
</style>
